/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.common.security.app;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.pig4cloud.pigx.common.security.component.PigxPreAuthenticationChecks;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author lengleng
 * @date 2018/8/5
 * 手机登录校验逻辑
 * 验证码登录、社交登录
 */
@Slf4j
public class AppAuthenticationProvider extends DaoAuthenticationProvider implements AuthenticationProvider {

	private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
	private UserDetailsChecker detailsChecker = new PigxPreAuthenticationChecks();

	private final String encodeKey = "pigxpigxpigxpigx";
	private static final String KEY_ALGORITHM = "AES";

	@Getter
	@Setter
	private DelegatingPasswordEncoder passwordEncoder;

	@Getter
	@Setter
	private PigxUserDetailsService pigxUserDetailsService;

	@Override
	@SneakyThrows
	public Authentication authenticate(Authentication authentication) {

		AppAuthenticationToken appAuthenticationToken = (AppAuthenticationToken) authentication;

		String principal = appAuthenticationToken.getPrincipal().toString();


		UserDetails userDetails = pigxUserDetailsService.loadUserByAppName(principal);
		if (userDetails == null) {
			log.debug("Authentication failed: no credentials provided");

			throw new BadCredentialsException(messages.getMessage(
					"AbstractUserDetailsAuthenticationProvider.noopBindAccount",
					"Noop Bind Account"));
		}

		// 检查账号状态
		detailsChecker.check(userDetails);

		String presentedPassword = new String(authentication.getCredentials().toString().getBytes(), "utf-8");
		String  password = decryptAES(URLUtil.decode(userDetails.getPassword(), "utf-8"), encodeKey).trim();

		System.out.println(presentedPassword.equals(password));
		if(!presentedPassword.equals(password)){
			logger.debug("Authentication failed: password does not match stored value");

			throw new BadCredentialsException(messages.getMessage(
					"AbstractUserDetailsAuthenticationProvider.badCredentials",
					"Bad credentials"));
		}

	//	additionalAuthenticationChecks(userDetails, appAuthenticationToken);

		AppAuthenticationToken authenticationToken = new AppAuthenticationToken(userDetails, userDetails.getAuthorities());
		authenticationToken.setDetails(appAuthenticationToken.getDetails());
		return authenticationToken;
	}


	@Override
	public boolean supports(Class<?> authentication) {
		if(authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class)){
			return false;
		}
		return AppAuthenticationToken.class.isAssignableFrom(authentication);
	}

	private static String decryptAES(String data, String pass) {
		AES aes = new AES(Mode.CBC, Padding.NoPadding,
				new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM),
				new IvParameterSpec(pass.getBytes()));
		byte[] result = aes.decrypt(Base64.decode(data.getBytes(StandardCharsets.UTF_8)));
		return new String(result, StandardCharsets.UTF_8);
	}

}
